import React, { useRef } from 'react';
import {
  ModalForm,
  ProFormRadio,
  ProFormTreeSelect,
  ProFormText,
  ProFormDependency,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useIntl, useAccess } from 'umi';
import { getTree } from '@/utils';
import { getMenurule, addItem, updateItem } from '@/services/menurule';
import { message } from 'antd';

type AddEditProps = {
  visible: boolean;
  row?: Partial<API.RuleListItem>;
  defaultMenuType?: string;
  onClose?: () => void;
  onSuccess?: () => void;
};

const AddEdit: React.FC<AddEditProps> = (props) => {
  const { visible, row, defaultMenuType = 'btn', onClose, onSuccess } = props;
  const handleVisibleChange = (show: boolean) => {
    if (!show) {
      onClose?.();
    }
  };
  const intl = useIntl();
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();
  const getMenuList = async () => {
    const { data, code } = await getMenurule({ type: 'menu', _all: 'ty' });
    if (code === 0) {
      return [
        {
          id: 0,
          title: intl.formatMessage({ id: 'public.rootLayer' }),
          children: getTree(
            data.data.map((item: API.RuleListItem) => ({
              ...item,
              disabled: item.id === (row && row.id),
            })),
          ),
        },
      ];
    }
    return [];
  };
  const handleSubmit = async (values: API.RuleListItem) => {
    if (!access.isAdmin) {
      message.warning(
        intl.formatMessage({ id: row ? 'public.noUpdatePermission' : 'public.noAddPermission' }),
      );
      return true;
    }
    const { code } = row ? await updateItem({ ...values, id: row.id }) : await addItem(values);
    if (code === 0) {
      message.success(intl.formatMessage({ id: 'public.successTips' }));
      onSuccess?.();
      return true;
    }
    return false;
  };
  return (
    <ModalForm
      formRef={formRef}
      title={
        intl.formatMessage({
          id: row ? 'public.edit' : 'public.add',
        }) +
        intl.formatMessage({
          id: 'menurule.menu',
        })
      }
      width="800px"
      layout="vertical"
      grid={true}
      rowProps={{
        gutter: 24,
      }}
      // labelCol={{ span: 6 }}
      // wrapperCol={{ span: 18 }}
      visible={visible}
      onVisibleChange={handleVisibleChange}
      modalProps={{ centered: true, destroyOnClose: true, maskClosable: false }}
      onFinish={handleSubmit}
      onValuesChange={(target) => {
        if (target.type) {
          formRef.current?.setFieldValue('position', '');
        }
      }}
      initialValues={
        row
          ? { ...row }
          : {
              type: defaultMenuType,
              status: 1,
              not_power: 0,
            }
      }
    >
      <ProFormRadio.Group
        colProps={{
          span: 12,
        }}
        label={intl.formatMessage({ id: 'menurule.type' })}
        name="type"
        // initialValue={row ? row.type : 'menu'}
        options={[
          {
            value: 'menu',
            label: intl.formatMessage({ id: 'menurule.menu' }),
          },
          {
            value: 'btn',
            label: intl.formatMessage({ id: 'menurule.btn' }),
          },
          {
            value: 'tag',
            label: intl.formatMessage({ id: 'menurule.tag' }),
          },
          {
            value: 'api',
            label: intl.formatMessage({ id: 'menurule.api' }),
          },
        ]}
      />

      <ProFormDependency key="pid" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type !== 'api') {
            return (
              <ProFormTreeSelect
                colProps={{
                  span: 12,
                }}
                name="pid"
                // initialValue={row && row.pid}
                label={intl.formatMessage({ id: 'public.pid' })}
                style={{ width: '100%' }}
                placeholder={intl.formatMessage({ id: 'public.placeholder.select' })}
                fieldProps={{
                  // showArrow: false,
                  // filterTreeNode: true,
                  // showSearch: true,
                  // dropdownMatchSelectWidth: false,
                  // labelInValue: true,
                  treeDefaultExpandAll: true,
                  allowClear: true,
                  // autoClearSearchValue: true,
                  // multiple: true,
                  treeNodeFilterProp: 'id',
                  treeNodeLabelProp: 'title',
                  fieldNames: {
                    label: 'title',
                    value: 'id',
                  },
                }}
                request={getMenuList}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'public.rules.pid' }),
                  },
                ]}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormDependency key="position" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type === 'menu' || type === 'btn') {
            return (
              <ProFormRadio.Group
                colProps={{
                  span: 12,
                }}
                label={intl.formatMessage({ id: 'menurule.position' })}
                name="position"
                // initialValue={row ? row.position : ''}
                options={
                  type === 'menu'
                    ? [
                        {
                          value: 'top',
                          label: intl.formatMessage({ id: 'menurule.top' }),
                        },
                        {
                          value: 'left',
                          label: intl.formatMessage({ id: 'menurule.left' }),
                        },
                      ]
                    : [
                        {
                          value: 'table-top-left',
                          label: intl.formatMessage({ id: 'menurule.table-top-left' }),
                        },
                        {
                          value: 'table-top-right',
                          label: intl.formatMessage({ id: 'menurule.table-top-right' }),
                        },
                        {
                          value: 'td-operate',
                          label: intl.formatMessage({ id: 'menurule.td-operate' }),
                        },
                      ]
                }
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'menurule.rules.position' }),
                  },
                ]}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormDependency key="name" name={['type']} ignoreFormListField>
        {({ type }) => {
          return (
            <ProFormText
              colProps={{
                span: 12,
              }}
              name="name"
              // initialValue={row ? row.name : ''}
              label={intl.formatMessage({
                id: `menurule.${type === 'api' ? 'apiname' : type === 'btn' ? 'btnname' : 'name'}`,
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: `menurule.rules.${
                      type === 'api' ? 'apiname' : type === 'btn' ? 'btnname' : 'name'
                    }`,
                  }),
                },
              ]}
            />
          );
        }}
      </ProFormDependency>
      <ProFormDependency key="title" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type !== 'api') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="title"
                // initialValue={row ? row.title : ''}
                label={intl.formatMessage({
                  id: `menurule.${type === 'btn' ? 'btntitle' : 'title'}`,
                })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'menurule.rules.title' }),
                  },
                ]}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormDependency key="path" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type === 'menu') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="path"
                // initialValue={row ? row.path : ''}
                label={intl.formatMessage({ id: 'menurule.path' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'menurule.rules.path' }),
                  },
                ]}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="remark"
        // initialValue={row ? row.remark : ''}
        label={intl.formatMessage({ id: 'menurule.remark' })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'menurule.rules.remark' }),
          },
        ]}
      />
      <ProFormDependency key="redirect" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type === 'menu') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="redirect"
                // initialValue={row ? row.redirect : ''}
                label={intl.formatMessage({ id: 'menurule.redirect' })}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="api"
        // initialValue={row ? row.api : ''}
        label={intl.formatMessage({ id: 'menurule.api' })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'menurule.rules.api' }),
          },
        ]}
      />
      <ProFormDependency key="component" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type === 'menu' || type === 'tag') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="component"
                // initialValue={row ? row.component : ''}
                label={intl.formatMessage({ id: 'menurule.component' })}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormDependency key="icon" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type !== 'api') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="icon"
                // initialValue={row ? row.icon : ''}
                label={intl.formatMessage({ id: 'menurule.icon' })}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormDependency key="sort" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type !== 'api') {
            return (
              <ProFormText
                colProps={{
                  span: 12,
                }}
                name="sort"
                // initialValue={row && row.sort}
                label={intl.formatMessage({ id: 'menurule.sort' })}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
      <ProFormRadio.Group
        colProps={{
          span: 12,
        }}
        label={intl.formatMessage({ id: 'public.status' })}
        name="status"
        // initialValue={row ? row.status : 1}
        options={[
          {
            value: 1,
            label: intl.formatMessage({ id: 'menurule.visible' }),
          },
          {
            value: 2,
            label: intl.formatMessage({ id: 'menurule.hidden' }),
          },
          {
            value: 3,
            label: intl.formatMessage({ id: 'menurule.disabled' }),
          },
        ]}
      />
      <ProFormDependency key="permission" name={['type']} ignoreFormListField>
        {({ type }) => {
          if (type !== 'api') {
            return (
              <ProFormRadio.Group
                colProps={{
                  span: 12,
                }}
                label={intl.formatMessage({ id: 'menurule.is_permission' })}
                name="not_power"
                // initialValue={row ? row.not_power : 0}
                options={[
                  {
                    value: 1,
                    label: intl.formatMessage({ id: 'public.yes' }),
                  },
                  {
                    value: 0,
                    label: intl.formatMessage({ id: 'public.no' }),
                  },
                ]}
              />
            );
          }
          return null;
        }}
      </ProFormDependency>
    </ModalForm>
  );
};

export default AddEdit;
